/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.eit.ntc.lmsbackend.struts.action;

import com.eit.ntc.lmsbackend.struts.form.LMSForm;
import com.eit.ntc.lmsbackend.utils.RoleUtils;
import com.eit.ntc.spring.utils.DateTimeUtils;
import com.eit.ntc.struts.action.AbstractWebFlowAction;
import com.eit.toschoolonline.lms.jdo.DocumentItemM;
import com.eit.toschoolonline.lms.jdo.LearningItemM;
import com.eit.toschoolonline.lms.jdo.LessonM;
import com.eit.toschoolonline.lms.jdo.SubjectM;
import com.eit.toschoolonline.lms.service.DocumentItemService;
import com.eit.toschoolonline.lms.service.LearningItemService;
import com.eit.toschoolonline.lms.service.LessonService;
import com.eit.toschoolonline.lms.service.SubjectService;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import org.apache.struts.upload.FormFile;
import org.springframework.validation.Errors;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

/**
 *
 * @author chanon
 */
public class EdocAction extends AbstractWebFlowAction {

    private LessonService lessonService;
    private SubjectService subjectService;
    private LearningItemService learningItemService;
    private DocumentItemService documentItemService;
    //private static String pathEdoc = "c:/content/Edoc";
    public Event saveUpdateFileDoc(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        String zipfileFlag = getHttpServletRequestParameter(context, "zipfile");
        boolean iszip = false;
        if (zipfileFlag != null && zipfileFlag.trim().equals("iszip")) {
            iszip = true;
        }
        ;
        //FormFile dFile = getFormFile(context, "docFile");
        String dFileName = (String) getHttpServletSessionAttribute(context, "temp_filename");
        removeHttpServletSessionAttribute(context, "temp_filename");
        File dFile = new File(dFileName);
        long dFileSize = 0;
        if (dFile!=null){

                dFileName = dFile.getName();

                dFileSize = dFile.length();
            };
        if (dFile != null && !dFileName.equals("") && dFileSize > 0) {
            DocumentItemM docItem = lForm.getDocumentItemM();
            //String filename = lForm.getDocFilename();
            String filename = getHttpServletRequestParameter(context, "docFilename");
            if (filename == null || filename.trim().equals("")) {
                //filename = dFile.getFileName();
                filename = (String) getHttpServletSessionAttribute(context, "temp_name");
                    removeHttpServletSessionAttribute(context, "temp_name");
            }
            ;
            docItem.setFilename(filename);
            int nextItemCode = learningItemService.getMaxItemCode();
            docItem.setItemCode(nextItemCode + 1);
            docItem = documentItemService.updateDoc(docItem, dFile, iszip); 
            lForm.setDocumentItemM(docItem);

            return success();
        } else {
            Errors errors = getFormErrors(context);
            errors.rejectValue("docFile", "errors.FileNotFound", "File Not Found");
            return error();
        }
    }

    public Event cancelUpdateFileDoc(RequestContext context) throws Exception {
        return success();
    }

    public Event MainDoc(RequestContext context) throws Exception {

        LMSForm lForm = (LMSForm) getFormObject(context);
        lForm.setSubjectM(null);
        lForm.setLessonM(null);
        lForm.getLessonList().clear();
        lForm.getSubjectList().clear();
        lForm.getEdocList().clear();
        lForm.setSelectSubject("");
        lForm.getItemList().clear();
        lForm.setActiveSelect("");
        lForm.setErrorMode("");
        lForm.setItemM(null);
        lForm.setActiveSelect("");
        SubjectService sservice = getSubjectService();
        lForm.setSubjectList(sservice.getSubjectAll());
        return new Event(this, "success");
    }

    public Event GetActiveDoc(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        SubjectService sservice = getSubjectService();
        lForm.getEdocList().clear();
        SubjectM s = sservice.getSubjectByCode(lForm.getSelectSubject());
        DocumentItemService dservice = getDocumentItemService();
        lForm.setEdocList(dservice.getDocBySubject(s));
        lForm.setSubjectM(s);
        return new Event(this, "success");
    }

    public Event AddDoc(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        lForm.setActiveSelect("");
        lForm.setDocName("");
        lForm.setDocOwner("");
        lForm.setDocType("");
        lForm.setErrorMode("");
        lForm.setSubjectM(null);
        // lForm.setZipfile(false);
        lForm.setItemDescription("");
        lForm.setItemKeyword("");
        return new Event(this, "success");
    }

    public Event SelectDocSubject(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        lForm.setActiveSelect("OPEN");
        lForm.setDocName("");
        lForm.setDocOwner("");
        lForm.setDocType("");
        lForm.setErrorMode("");
        lForm.setItemDescription("");
        lForm.setItemKeyword("");
        LessonService lservice = getLessonService();
        SubjectService sservice = getSubjectService();
        SubjectM s = sservice.getSubjectByCode(lForm.getSelectSubject());
        lForm.setSubjectM(s);
        lForm.setLessonList(lservice.getLessonBySubject(s.getSubjectCode()));
        return success();
    }

    public Event DelDoc(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        DocumentItemService dservice = getDocumentItemService();
        DocumentItemM d = dservice.getDoc(Integer.parseInt(lForm.getInputID()));
        d.setStatus(DocumentItemM.DISABLE_STATUS);
        dservice.updateDoc(d);

        return success();
    }

    public Event EditDoc(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);
        DocumentItemService dservice = getDocumentItemService();
        String itemID = getHttpServletRequestParameter(context, "id");
        lForm.setErrorMode("");
        DocumentItemM d = dservice.getDoc(Integer.parseInt(itemID));
        lForm.setDocName(d.getDocName());
        lForm.setDocOwner(d.getOwner());
        lForm.setDocType(d.getType());
        lForm.setDocumentItemM(d);
        lForm.setItemDescription(d.getItemDesc());
        lForm.setItemKeyword(d.getKeyword());
        //  lForm.setZipfile(false);
        return new Event(this, "success");
    }

    public Event SaveEditDoc(RequestContext context) throws Exception {

        LMSForm lForm = (LMSForm) getFormObject(context);
        DocumentItemService dservice = getDocumentItemService();
        lForm.setErrorMode("");

//       
//        FormFile dFile = getFormFile(context,"docFile");
//                lForm.getDocFile();
//        //Create Path
//        String path ="";
//        
//            path = "c:/learningitem/"+dFile.getFileName();
// 
//      //  Read & write File
//       
//        byte[] dFileData = dFile.getFileData();
//        
//        FileOutputStream fosDown = new FileOutputStream(path);
//                fosDown.write(dFileData);
//                fosDown.close();

        DocumentItemM itemM = lForm.getDocumentItemM();
        itemM.setUpdateDate(DateTimeUtils.getEngNow());
        itemM.setDocName(lForm.getDocName());
        //itemM.setFilename(dFile.getFileName());           
        itemM.setType(lForm.getDocType());
        itemM.setOwner(lForm.getDocOwner());
        //itemM.setUserRole();
        itemM.setItemDesc(lForm.getItemDescription());
        itemM.setKeyword(lForm.getItemKeyword());
        dservice.updateDoc(itemM);


        return new Event(this, "success");
    }

    public Event SaveDoc(RequestContext context) throws Exception {


        LMSForm lForm = (LMSForm) getFormObject(context);
        Errors errors = getFormErrors(context);
        String zipfileFlag = getHttpServletRequestParameter(context, "zipfile");
        boolean iszip = false;
        if (zipfileFlag != null && zipfileFlag.trim().equals("iszip")) {
            iszip = true;
        }
        ;
        DocumentItemService dservice = getDocumentItemService();
        LessonService lservice = getLessonService();
        LearningItemService liservice = getLearningItemService();
        LessonM l = lservice.getLesson(Integer.parseInt(lForm.getSelectLesson()));
        lForm.setErrorMode("");
        int max = liservice.getMaxItemCode() + 1;
        FormFile dFile = getFormFile(context, "docFile");
        System.out.println("+++++++++++++++++++++++++++++++++++" + dFile.getContentType());
        if (dFile.getFileName() != null && !dFile.getFileName().equals("")) {

            String filename = lForm.getDocFilename();
            if (filename == null || filename.trim().equals("")) {
                if (iszip) {
                    errors.reject("errors.UploadZipFileName");
                    return error();
                }
                filename = dFile.getFileName();
            }
            ;

            //Create Path
//        String path ="";
//
//       path = pathEdoc+"/"+max+"/"+dFile.getFileName();
////         if(lForm.getDocType().equals("flashpaper")){
////            path = "c:/ntc/edoc/flashpaper/"+max+"/"+dFile.getFileName();
////         }else if(lForm.getDocType().equals("html")){
////            path = "c:/ntc/edoc/html/"+max+"/"+dFile.getFileName();
////         }else if(lForm.getDocType().equals("swfvdo")){
////            path = "c:/ntc/edoc/swfvdo/vdo/"+max+"/"+dFile.getFileName();
////         }else if(lForm.getDocType().equals("wma")){
////            path = "c:/ntc/edoc/wma/vdo/"+max+"/"+dFile.getFileName();
////         }else if(lForm.getDocType().equals("SCORM ZIP")){
////            path = "c:/ntc/edoc/scorm/"+max+"/"+dFile.getFileName();
////         }
//
//        File pathFile = new File(path);
//        File newpath = pathFile.getParentFile();
//        newpath.mkdirs();
//      //  Read & write File
//
//        byte[] dFileData = dFile.getFileData();
//
//        FileOutputStream fosDown = new FileOutputStream(path);
//                fosDown.write(dFileData);
//                fosDown.close();

            DocumentItemM itemM = new DocumentItemM();
            itemM.setCreateDate(DateTimeUtils.getEngNow());

            itemM.setItemCode(max);
            itemM.setDocName(lForm.getDocName());

            itemM.setFilename(filename);
            itemM.setType(lForm.getDocType());
            itemM.setItemType(LearningItemM.EDOCUMENT_TYPE);
            itemM.setLessonId(l);
            itemM.setLessonName(l.getLessonName());
            itemM.setOwner(lForm.getDocOwner());
            String role = RoleUtils.getRole(context);
            itemM.setUserRole(role);
            itemM.setOfflineCode(max);
            if (lForm.getDocType().equals("swfvdo") || lForm.getDocType().equals("wma")) {
                itemM.setLink(lForm.getDocType() + "/vdo/" + max + "/" + itemM.getFilename());
            } else {
                itemM.setLink(lForm.getDocType() + "/" + max + "/" + itemM.getFilename());
            }
            itemM.setStatus("ENABLE");
            itemM.setSubjectName(lForm.getSubjectM().getSubjectName());
            itemM.setItemDesc(lForm.getItemDescription());
            itemM.setKeyword(lForm.getItemKeyword());
            itemM = dservice.createDoc(itemM, dFile.getFileData(), iszip);



            return new Event(this, "success");
        } else {
            lForm.setErrorMode("กรุณาระบุไฟล์");
            return new Event(this, "unFile");
        }
    }

    public Event CancelDoc(RequestContext context) throws Exception {
        LMSForm lForm = (LMSForm) getFormObject(context);

        return new Event(this, "success");
    }

    public LessonService getLessonService() {
        return lessonService;
    }

    public void setLessonService(LessonService lessonService) {
        this.lessonService = lessonService;
    }

    public SubjectService getSubjectService() {
        return subjectService;
    }

    public void setSubjectService(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    public LearningItemService getLearningItemService() {
        return learningItemService;
    }

    public void setLearningItemService(LearningItemService learningItemService) {
        this.learningItemService = learningItemService;
    }

    public DocumentItemService getDocumentItemService() {
        return documentItemService;
    }

    public void setDocumentItemService(DocumentItemService documentItemService) {
        this.documentItemService = documentItemService;
    }
}
